package com.dq.service.record.impl;

import com.dq.controller.in.query.IntegralQuery;
import com.dq.domain.sys.user.Integral;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.ShiroService;
import com.dq.service.record.IntegralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @Author luchangtong
 * @Date 2019/12/7 17:39
 */
@Service
public class IntegralServiceImpl implements IntegralService {

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private ShiroService shiroService;

    @Override
    public List<Integral> findByWhere(IntegralQuery integralQuery) {
        StringBuilder hql = new StringBuilder("select u from Integral u where u.deleted=false");
        Query q = createWhereHql(integralQuery,hql);
        q.setFirstResult((integralQuery.getPage()-1)*integralQuery.getSize());
        q.setMaxResults(integralQuery.getSize());
        List<Integral> list = q.getResultList();
        return list;
    }

    @Override
    public Long countByWhere(IntegralQuery integralQuery) {
        StringBuilder hql = new StringBuilder("select count(u) from Integral u where u.deleted=false");
        Query q = createWhereHql(integralQuery,hql);
        return new Long((long) q.getResultList().get(0));
    }

    public Query createWhereHql(IntegralQuery integralQuery,StringBuilder hql){
        SysUser user = shiroService.getUser();
        if(user != null){
            hql.append(" and u.user =:user");
        }
        if(integralQuery.getChangeType() != null){
            hql.append(" and u.changeType =:changeType");
        }
        if(integralQuery.getCiType() != null){
            hql.append(" and u.ciType =:ciType");
        }
        if(integralQuery.getBeginTime() != null){
            hql.append(" and u.createTime >=:beginTime");
        }
        if(integralQuery.getEndTime() != null){
            hql.append(" and u.createTime <=:endTime");
        }
        hql.append(" order By u.createTime desc");
        Query query = entityManager.createQuery(hql.toString());
        if(user != null){
            query.setParameter("user",user);
        }
        if(integralQuery.getChangeType() != null){
            query.setParameter("changeType",integralQuery.getChangeType());
        }
        if(integralQuery.getCiType() != null){
            query.setParameter("ciType",integralQuery.getCiType());
        }
        if(integralQuery.getBeginTime() != null){
            query.setParameter("beginTime",integralQuery.getBeginTime());
        }
        if(integralQuery.getEndTime() != null){
            query.setParameter("endTime",integralQuery.getEndTime());
        }
        return query;
    }
}
